#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>

void writer(int wfd)
{
    const char* str = "Hello father, I am your child";
    pid_t pid = getpid();
    int cnt = 0;
    char buffer[128];
    while(1)
    {
        snprintf(buffer, sizeof(buffer), "message: %s, pid: %d, count: %d\n", str, pid, cnt++);
        write(wfd, buffer, strlen(buffer));
        sleep(1);
    }

}

void reader(int rfd)
{
    char buffer[1024];
    while(1)
    {
        ssize_t n = read(rfd, buffer, sizeof(buffer) - 1);
        (void)n;
        printf("Father gets a message: %s", buffer);
    }
}



int main()
{
   // 1. 创建管道
   int pipefd[2];
   int n = pipe(pipefd);
   /* pipefd[0]: read, pipefd[1]: write*/
   if(n < 0) return 1;
   printf("pipefd[0]: %d, pipefd[1]: %d", pipefd[0], pipefd[1]);

   // 2. 创建子进程
   pid_t id = fork();
   if(id == 0)
   {
       // 子进程: w
       close(pipefd[0]);
       writer(pipefd[1]);

       exit(0);
   }
   // 父进程: r
   
   close(pipefd[1]);
   reader(pipefd[0]);
   // 进程等待
   wait(NULL);
    return 0;
}
